<template>
  <div>
    <MBX Biao="商品管理" Biao1="参数列表"></MBX>
    <el-card class="mt">
      <el-alert title="只允许为三级分类设置参数" type="warning" show-icon> </el-alert>

      <div class="mt">
        <span class="demonstration">选择商品分类：</span>
        <el-cascader
          v-model="checkedArr"
          :options="goodsCate"
          :props="addProps"
          @change="handleChange"
        ></el-cascader>
      </div>

      <el-tabs class="mt" v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button :disabled="isOk" type="primary" @click="addCs">添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table class="mt" border :data="manyParames">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  :key="index"
                  v-for="(item, index) in scope.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(index, scope.row)"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
              <el-button type="primary" size="mini" icon="el-icon-edit" @click='bjDc(scope.row)'>编辑</el-button>
              <el-button type="danger" size="mini" icon="el-icon-delete" @click='delCs(scope.row)'>删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>


        <el-tab-pane label="静态参数" name="only">
          <el-button :disabled="isOk" type="primary" @click="addCsSx">添加属性</el-button>
          <!-- 静态属性表格 -->
          <el-table class="mt" border :data="onlyParames">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  :key="index"
                  v-for="(item, index) in scope.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(index, scope.row)"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
              <el-button type="primary" size="mini" icon="el-icon-edit"  @click='bjDc(scope.row)'>编辑</el-button>
              <el-button type="danger" size="mini" icon="el-icon-delete" @click='delCs(scope.row)'>删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数的弹框 -->
    <el-dialog @close='chongzhi' title="添加动态参数" :visible.sync="dialogFormVisiblecs">
      <el-form :model="formcs" ref="yanzhen" :rules="Rules">
        <el-form-item label="动态参数" :label-width="formLabelWidth" prop="attr_name">
          <el-input v-model="formcs.attr_name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisiblecs = false">取 消</el-button>
        <el-button type="primary" @click="addDongTai">确 定</el-button>
      </div>
    </el-dialog>
    <!--  -->


       <!-- 添加属性的弹框 -->
    <el-dialog @close='chongzhi' title="添加静态属性" :visible.sync="dialogFormVisiblesx">
      <el-form :model="formcs" ref="yanzhen" :rules="Rules">
        <el-form-item label="静态属性" :label-width="formLabelWidth" prop="attr_name">
          <el-input v-model="formcs.attr_name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisiblesx = false">取 消</el-button>
        <el-button type="primary" @click="addDongJtai">确 定</el-button>
      </div>
    </el-dialog>
    <!--  -->


    <!-- 编辑动态参数 -->
    <el-dialog title="编辑动态参数" :visible.sync="dialogFormVisiblebj">
      <el-form :model="formbj" ref="yanzhen" :rules="Rules">
        <el-form-item label="动态参数" :label-width="formLabelWidth" prop="attr_name">
          <el-input v-model="formbj.attr_name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisiblebj = false">取 消</el-button>
        <el-button type="primary" @click="editDongTai">确 定</el-button>
      </div>
    </el-dialog>
    <!--  -->
  </div>
</template>

<script>
import { getCatel, getCshu, addCanShu, delCanShu, addDongC } from "@/http/api";
export default {
  data() {
    return {
      dialogFormVisiblecs: false, //添加参数的弹框
      dialogFormVisiblebj: false, //编辑参数的弹框
      dialogFormVisiblesx:false,//添加静态属性
      formcs: {
        attr_name: "",
      },
      formbj: {
        attr_name: "",
      },
      Rules: {
        attr_name: [{ required: true, message: "请输入活动名称", trigger: "blur" }],
      },
      inputVisible: false,
      inputValue: "",
      manyParames: [], //动态参数
      onlyParames: [], //静态参数
      goodsCate: [], //商品分类
      value: [],
      checkedArr: [], //获取商品分类数据数组
      addProps: {
        //级联配置
        expandTrigger: "hover",
        label: "cat_name",
        value: "cat_id",
        children: "children",
      },
      activeName: "many",
      formLabelWidth: "100px",
    };
  },
  created() {
    this.getCart();
  },
  computed: {
    isOk() {
      //按钮禁用
      return this.checkedArr.length !== 3 ? true : false;
    },
    cate_id() {
      return this.checkedArr[this.checkedArr.length - 1];
    },
  },
  methods: {
    //添加静态属性提交
    addDongJtai(){
       //验证表单是否有效
      this.$refs.yanzhen.validate(async (valid) => {
        console.log(valid);
        if (!valid) return;

        //调用添加参数接口
        const res = await addDongC(this.cate_id, {
          attr_name: this.formcs.attr_name,
          attr_sel: this.activeName,
        });

        //刷新参数列表
        // this.getCart();
        this.getGoodsList();
        //影藏弹框
        this.dialogFormVisiblesx = false;
      });
    },
    //添加静态属性
    addCsSx(){
       this.dialogFormVisiblesx=true
    },
    //删除参数
    async delCs(row){
      const res=await this.$confirm('你敢删我, 嗯?', '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch((error) => {
          this.$message({
            type: 'error',
            message: '已取消删除'
          });          
        })
        
        if(res==='confirm'){
          await delCanShu(this.cate_id,row.attr_id)
          //调用重新渲染
          this.getGoodsList();
        }
   
      // const res=await delCanShu(this.cate_id,row.attr_id)
      // this.getGoodsList();

    },
    //重置清空
    chongzhi(){
      this.formcs.attr_name=''
    },
    //编辑动态参数确定提交
    editDongTai(){
        this.$refs.yanzhen.validate(async (valid) => {
        console.log(valid);
        if (!valid) return;

        //调用添加参数接口
        const res = await addCanShu(this.cate_id,this.formbj.attr_id, {
          attr_name: this.formbj.attr_name,
          attr_sel: this.activeName,
          attr_vals: this.formbj.attr_vals
        });

        //刷新参数列表
        // this.getCart();
        this.getGoodsList();
        //影藏弹框
        this.dialogFormVisiblebj = false;
      });
    },
    //编辑动态参数弹出弹框
    bjDc(row){
       this.dialogFormVisiblebj=true;
       this.formbj.attr_name=row.attr_name
       this.formbj.attr_id=row.attr_id
       this.formbj.attr_vals=row.attr_vals.join(",")//转换为字符串
    },
    //确定向后台添加新的参数
    addDongTai() {
      //验证表单是否有效
      this.$refs.yanzhen.validate(async (valid) => {
        console.log(valid);
        if (!valid) return;

        //调用添加参数接口
        const res = await addDongC(this.cate_id, {
          attr_name: this.formcs.attr_name,
          attr_sel: this.activeName,
        });

        //刷新参数列表
        // this.getCart();
        this.getGoodsList();
        //影藏弹框
        this.dialogFormVisiblecs = false;
      });
    },
    //添加参数弹出弹框
    addCs() {
      this.dialogFormVisiblecs = true;
    },
    showInput(row) {
      console.log("点击按钮时触发",row);
      row.inputVisible = true;
      //使用$nextTick获取焦点
      this.$nextTick((_) => {
        console.log("this.$refs.saveTagInput", this.$refs.saveTagInput);
        this.$refs.saveTagInput.focus();
      });
    },
    //敲回车或者失去焦点的时候添加数据，隐藏输入框并显示按钮
    async handleInputConfirm(row) {
      console.log("敲回车或者失去焦点的时候添加数据，隐藏输入框并显示按钮");

      if (row.inputValue.trim().length === 0) return;
      row.attr_vals.push(row.inputValue);

      //调用更新参数接口提交到后台数据库
      const res = await addCanShu(this.cate_id, row.attr_id, {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(","),
      });

      //更新参数列表
      this.getCart();
      row.inputVisible = false;
      //清空之前输入的数据
      row.inputValue = "";
    },

    //删除tag
    async handleClose(index, row) {
      console.log("删除tag时的回调函数");
      row.attr_vals.splice(index, 1);
      const res = await delCanShu(this.cate_id, row.attr_id, {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(","),
      });
    },
    //点击tab栏触发
    handleClick() {
      console.log("点击tab栏触发", this.activeName);
      this.getGoodsList();
    },
    async getCart() {
      const res = await getCatel();
      console.log("分类参数数据获取", res);
      this.goodsCate = res;
    },
    // handleChange() {
    //   console.log("选择商品分类");
    // },
    // handleClick(tab, event) {
    //   console.log(tab, event);
    // },
    handleChange() {
      //级联选择器改变时触发
      this.getGoodsList();
    },
    async getGoodsList() {
      //获取参数列表的方法
      console.log("获取参数列表的方法");
      if (this.checkedArr.length !== 3) {
        this.$message({
          type: "warning",
          message: "你需要选择三级分类，才能添加或编辑",
        });
        //清空参数表格
        this.manyParames = [];
        //清空属性表格
        this.onlyParames = [];
        return;
      }

      //调用参数列表接口渲染参数列表
      const res = await getCshu(this.cate_id, this.activeName);
      console.log("参数接口渲染参数列表", res);

      //遍历给每个对象添加inputVisible，inputValue
      res.forEach((item) => {
        item.inputVisible = false;
        item.inputValue = "";
      });
      if (this.activeName === "many") {
        //渲染动态参数列表
        res.forEach((item) => {
          item.attr_vals = item.attr_vals.length > 0 ? item.attr_vals.split(",") : [];
        });
        console.log("已转换为数组的attr_vals", res);
        this.manyParames = res; //将动态参数赋值到动态参数的数组
      } else if (this.activeName === "only") {
        res.forEach((item) => {
          item.attr_vals = item.attr_vals.length > 0 ? item.attr_vals.split(",") : [];
        });
        console.log("已转换为静态数组的attr_vals", res);
        this.onlyParames = res;
      }
    },
  },
};
</script>

<style scoped>
.el-tag {
  margin: 6px 10px;
}
.input-new-tag {
  width: 80px;
}
</style>
